<template>
  <view class="user-info-content">
    <view class="user-info-form">
      <up-cell-group>
        <up-cell title="更改头像" @click="uploadAvatar = true && isEdit">
          <template #value>
            <!-- <up-image :show-loading="true" :src="userInfo.avatar" width="80rpx" height="80rpx" shape="circle"></up-image> -->
            <up-avatar :src="userInfo.avatar" shape="circle"></up-avatar>
          </template>
        </up-cell>
        <up-cell title="昵称">
          <template #value>
            <text v-if="!isEdit">{{ userInfo.nickname }}</text>
            <up-input v-else v-model.trim="userInfo.nickname" border="none" inputAlign="right"></up-input>
          </template>
        </up-cell>
        <up-cell title="姓名">
          <template #value>
            <text v-if="!isEdit">{{ userInfo.name }}</text>
            <up-input v-else v-model.trim="userInfo.name" border="none" inputAlign="right"></up-input>
          </template>
        </up-cell>
        <up-cell title="性别" @click="showSex = true && isEdit">
          <template #value>
            <text>{{ genderName }}</text>
          </template>
        </up-cell>
        <up-cell title="手机号">
          <template #value>
            <text v-if="!isEdit">{{ userInfo.mobile || '请输入手机号' }}</text>
            <up-input v-else v-model="userInfo.mobile" :type="'number'" border="none" inputAlign="right"
              placeholder="请输入手机号"></up-input>
          </template>
        </up-cell>
        <up-cell title="公司" :border="false">
          <template #value>
            <text v-if="!isEdit">{{ userInfo.company || '请输入公司名称' }}</text>
            <up-input v-else v-model="userInfo.company" border="none" inputAlign="right"
              placeholder="请输入公司名称"></up-input>
          </template>
        </up-cell>
      </up-cell-group>

    </view>
    <up-action-sheet :show="showSex" :actions="actions" title="请选择性别" description="如果选择保密会报错" @close="showSex = false"
      @select="sexSelect">
    </up-action-sheet>

    <up-popup :show="uploadAvatar" :round="10" mode="bottom" bgColor="#ffffff" :closeable="false"
      closeIconPos="top-right" @close="uploadAvatar = false" :closeOnClickOverlay="false">
      <view class="upload-avatar-content">
        <up-button @click="getAvatar">上传头像</up-button>

        <view class="mt-[10rpx] mb-[30rpx] ">预览头像</view>
        <up-image v-if="selectAvatar" :src="selectAvatar.path" width="150rpx" height="150rpx" shape="circle"
          mode="aspectFill"></up-image>
        <up-image v-else :src="''" width="150rpx" height="150rpx" shape="circle" mode="aspectFill"></up-image>
        <view class="mt-[30rpx] flex">
          <up-button type="primary" size="small" shape="circle" @click="comfirmUpload">确认</up-button>
          <view class="w-[80rpx]">

          </view>
          <up-button type="warning" size="small" shape="circle" @click="handleCancelUpload">取消</up-button>
        </view>
      </view>
    </up-popup>


    <view class="operatin-btn">
      <up-button type="primary" v-if="!isEdit" text="确定" size="large" shape="circle" @click="handleEdit">修改</up-button>
      <up-button color="#eb8a1d" v-if="isEdit" text="确定" size="large" shape="circle" @click="hadnleSave">保存</up-button>
    </view>


    <!-- 消息提醒 -->
    <up-toast ref="uToastRef"></up-toast>
  </view>
</template>

<script>
import { getUserInfo, updateUserInfo } from '@/api/userinfo.js'
export default {
  components: {},
  data() {
    return {
      isEdit: false,
      labelStyle: {
        paddingLeft: '20rpx',
        fontSize: '28rpx'
      },
      uploadAvatar: false,
      showSex: false,
      userInfo: {
        avatar: "https://dthezntil550i.cloudfront.net/p4/latest/p42102052243097410008650553/1280_960/12bc8bc0-2186-48fb-b432-6c011a559ec0.png", // 用户头像链接或默认值
        nickname: "鸭头啤酒",  // 昵称
        name: "张三",          // 姓名
        gender: 1,          // 性别
        mobile: "",             // 手机号 
        company: ""            // 公司
      },
      actions: [
        { name: '男', value: 1 },
        { name: '女', value: 2 }
      ],
      selectAvatar: null
    }
  },
  computed: {
    genderName() {
      const data = this.actions.find(item => item.value === this.userInfo.gender);
      return data.name;
    }
  },
  created() {
    this.getUserInfos();
  },
  methods: {
    // 获取个人信息数据
    async getUserInfos() {
      try {
        const res = await getUserInfo();
        if (res.code === 2000) {
          this.userInfo = res.data;
          this.userInfo.gender = res.data.gender == '男' ? 1 : 2;
        } else {
          throw res.msg;
        }
      } catch (error) {
        console.log(error);
      }
    },
    handleEdit() {
      this.isEdit = true;
      this.$refs.uToastRef.show({
        type: 'default',
        message: "开始编辑",
        duration: 1000
      })
    },
    async hadnleSave() {
      try {
        const data = this.userInfo;
        const res = await updateUserInfo(data);
        if (res.code == 2000) {
          this.$refs.uToastRef.show({
            type: 'success',
            message: res.msg
          })
          this.isEdit = false;
        } else {
          this.handleErrors(res.msg)
        }
      } catch (error) {
        console.log(error);
      } finally {
        
      }
    },
    getAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.selectAvatar = res.tempFiles[0]; // 获取文件路径
        },
        fail: (err) => {
          console.error('选择图片失败:', err);
        }
      });
    },
    comfirmUpload() {
      if (!this.selectAvatar) {
        this.uploadAvatar = false;
        return;
      }
      uni.uploadFile({
        url: '/system/upload/file/', // 替换为你的真实接口地址
        filePath: this.selectAvatar.path,
        name: 'file',
        header: {
          'Content-Type': 'multipart/form-data' // 根据需要设置请求头
        },
        success: (uploadFileRes) => {
          this.userInfo.avatar = JSON.parse(uploadFileRes.data).data.url;
        },
        fail: (err) => {
          console.error('上传失败:', err);
        }
      });
      this.uploadAvatar = false;
    },
    handleCancelUpload() {
      this.uploadAvatar = false;
      this.selectAvatar = null;
    },
    sexSelect(e) {
      this.userInfo.gender = e.value;
    },
    handleErrors(errorData) {
      if (errorData) {
        for (const key in errorData) {
          if (errorData.hasOwnProperty(key)) {
            const errorMessages = errorData[key];
            if (Array.isArray(errorMessages)) {
              errorMessages.forEach((message) => {
                // 这里可以使用 uni.showToast 或其他方式展示错误信息
                uni.showToast({
                  title: `${key}: ${message}`,
                  icon: 'none',
                  duration: 2000
                });
              });
            }
          }
        }
      } else {
        console.error('未知错误:', errorData);
      }
    }
  },
  watch: {},

  // 页面周期函数--监听页面加载
  onLoad() { },
  // 页面周期函数--监听页面初次渲染完成
  onReady() { },
  // 页面周期函数--监听页面显示(not-nvue)
  onShow() {
  },
  // 页面周期函数--监听页面隐藏
  onHide() { },
  // 页面周期函数--监听页面卸载
  onUnload() { },
  // 页面处理函数--监听用户下拉动作
  // onPullDownRefresh() { uni.stopPullDownRefresh(); },
  // 页面处理函数--监听用户上拉触底
  // onReachBottom() {},
  // 页面处理函数--监听页面滚动(not-nvue)
  // onPageScroll(event) {},
  // 页面处理函数--用户点击右上角分享
  // onShareAppMessage(options) {},
}
</script>

<style lang="scss" scoped>
.user-info-content {
  width: 100%;
  min-height: 100vh;
  background: #f2f2f2;
  position: relative;
}

.user-info-form {
  background: #fff;
  // padding: 0 20rpx;
}

.operatin-btn {
  position: fixed;
  bottom: 20rpx;
  left: 0;
  right: 0;
  z-index: 999;
  padding: 0 30rpx;
}

.upload-avatar-content {
  width: 100%;
  height: 100%;
  padding: 80rpx 20rpx 80rpx;
  text-align: center;
}

:deep(.upload-avatar-content .u-image) {
  margin: 0 auto;
}
</style>